package com.platform.qujia.utils.tonglianpay.tlfusclasspay.struct;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.TreeMap;

import com.platform.qujia.utils.tonglianpay.tlfusclasspay.constant.CommonConstants;
import com.platform.qujia.utils.tonglianpay.tlfusclasspay.util.SignUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

/**
 * @author zzq
 * @version 1.0.0
 * @Title {@link}
 * @Description
 * @date 2020/5/26
 */
@Data
public class Request<T> implements Serializable {

    private static final long serialVersionUID = -1128445146065327824L;

    private String appId;
    private String version;
    private String charset;
    private String signType;
    private String sign;
    private String timestamp;
    private String service;
    private T bizContent;

    public void sign(String key) {
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId", appId);
        param.put("version", version);
        param.put("charset", charset);
        param.put("signType", signType);
        param.put("timestamp", timestamp);
        param.put("service", service);
        param.put("bizContent", JSON.toJSONString(bizContent));
        param.put("key", key);
        this.sign = SignUtils.sign(param);
    }

    public Map<String, String> toMap() {
        Map<String, String> param = new HashMap<>();
        param.put("appId", appId);
        param.put("version", version);
        param.put("charset", charset);
        param.put("signType", signType);
        param.put("timestamp", timestamp);
        param.put("service", service);
        param.put("sign", sign);
        param.put("bizContent", JSON.toJSONString(bizContent));
        return param;
    }

    public void verify(String result, String appKey) {
        JSONObject jsonObject = JSON.parseObject(result);
        TreeMap<String, String> resultParam = new TreeMap<>();
        for (Entry<String, Object> each : jsonObject.entrySet()) {
            resultParam.put(each.getKey(),
                Objects.nonNull(each.getValue()) ? String.valueOf(each.getValue()) : StringUtils.EMPTY);
        }
        resultParam.put("key", appKey);
        if (!SignUtils.verify(resultParam)) {
            throw new RuntimeException("验签不通过");
        }
    }

}
